
<script>
import BaseUrl from "@/http/request/BaseUrl";
import TokenAxios from "@/http/request/TokenAxios";

export default {
  data(){
    return{
      // 当前每页显示多少条数据
      pageSize: 10,
      //分页相关数据
      currentPage: this.$router.currentRoute.query.page ? parseInt(this.$router.currentRoute.query.page) : 1,
      tableData: [],
      parentTableData: [],
      total: 0,
      addDialogVisible: false,
      deleteTagById:false,
      openUpdateTypeByIds:false,
      // 添加分类的表单数据
      ruleForm: {
        name: '',
        isParent: '',
        isDisplay:'',
      },
      rules:{
        name: [
          {required: true, message: '请输入分类', trigger: 'blur'},
          {min: 2, max: 4, message: '长度在 2 到 4 个字符', trigger: 'blur'}
        ],
        isParent: [
          {required: true, message: '请至少给出一个序号，默认是1', trigger: 'blur'}
        ],
        isDisplay: [
          {required: true, message: '请至少给出一个序号，默认是0', trigger: 'blur'}
        ],
      },
      update:{
        name: '',
        isParent: '',
        isDisplay:','
      },
      types:{
        name: [
          {required: true, message: '请输入分类', trigger: 'blur'},
          {min: 2, max: 4, message: '长度在 2 到 4 个字符', trigger: 'blur'}
        ],
        isParent: [
          {required: true, message: '请至少给出一个序号，默认是1', trigger: 'blur'}
        ],
        isDisplay: [
          {required: true, message: '请至少给出一个序号，默认是0', trigger: 'blur'}
        ],
      }
    }
  },
  methods:{
    //新增标签
    addNewTagsById(){
      let url = BaseUrl.ADMIN_CONTENT + '/admin/type/insert';
      console.log(this.ruleForm)
      TokenAxios.post(url, this.ruleForm).then((response) => {
        let jsonResult = response.data;
        console.log(jsonResult);
        if (jsonResult.state == 20000) {
          this.$message({
            showClose: true,
            message: '添加分类成功！',
            type: 'success'
          });
          location.reload()
        } else {
          let title = '操作失败';
          this.$alert(jsonResult.message, title, {
            confirmButtonText: '确定',
            callback: action => {
            }
          });
        }
      }).catch(error => {
        let title = '错误';
        let message = '程序执行过程中出现错误，请打开浏览器的控制台查看详细错误信息！';
        this.$alert(message, title, {
          confirmButtonText: '确定',
          callback: action => {
          }
        });
        console.log(error);
      })
    },
    //
    openUpdateTypeById(type){
      this.openUpdateTypeByIds=true
      this.editTypeId=type.id
      console.log(this.editTypeId)
    },
    //修改分类名
    updateCategoryNameById(type){

      console.log('当前页面的type.id：', this.id);
      let requestBody = {
        name:type.name,
        parentId:type.parentId,
        isDisplay:type.isDisplay
      }

      let url = BaseUrl.ADMIN_CONTENT+'/admin/type/update/'+this.editTypeId;


      console.log(requestBody);
      TokenAxios.post(url,requestBody).then((response) => {
        let jsonResult = response.data;
        if (jsonResult.state == 20000) {
          this.$message({
            message: '成功!',
            type: 'success'
          });
          location.reload();
        } else {
          this.$alert(jsonResult.message, '错误', {
            confirmButtonText: '确定',
            callback: action => {
            }
          });
        }
      }).catch((error) => {
        console.log('请求出错:', error);
      });

    },
    //删除标签
    deleteTagsById(type){
      let message = '此操作将删除分类，是否继续？';
      this.id = type.id
      this.$confirm(message, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.handleDelete();
      }).catch(() => {
      });
    },
    handleDelete() {
      let url = BaseUrl.ADMIN_CONTENT + '/admin/type/delete/' + this.id;
      TokenAxios.post(url).then((response) => {
        let jsonResult = response.data;
        if (jsonResult.state == 20000) {
          this.$message({
            message: '删除成功!',
            type: 'success'
          });
          location.reload()
        } else {
          this.$alert(jsonResult.message, '错误', {
            confirmButtonText: '确定',
            callback: action => {
            }
          });
        }
      }).catch((error) => {
        console.log('请求出错:', error);
      });
    },
    // 切换分页
    handleCurrentChange(page) {
      // 修改当前页码时，使用 $router.push 而不是 $router.replace，保留浏览器的历史记录
      this.$router.replace('?page=' + page);
      this.loadUserList(page); // 将当前页码传递给 loadUserList 方法
    },
    loadUserList() {
      console.log('开始加载用户列表');
      let page = this.$router.currentRoute.query.page;
      console.log('开始加载用户列表，页码为', page);
      if (!page) {
        page = 1;
      }
      let url = BaseUrl.ADMIN_CONTENT + '/admin/type/listType?pageNum=' + page+'&pageSize='+this.pageSize;

      TokenAxios.get(url,page).then((response) => {
        console.log('当前页码：', this.currentPage);
        console.log('每页显示条数：', this.pageSize);
        console.log('请求 URL：', url);
        let jsonResult = response.data;
        if (jsonResult.state == 20000) {
          this.tableData = jsonResult.data.list;
          this.tableData.forEach((item) => {
            if (item.isDisplay == 0) {
              item.isDisplay = {
                text: '未显示',
                type: 'danger'
              };
            } else {
              item.isDisplay = {
                text: '显示',
                type: 'success'
              };
            };
            if (item.isParent == 1) {
              item.isParent = {
                text: '父类标签',
                type: 'danger'
              };
            } else {
              item.isParent = {
                text: '子类标签',
                type: 'success'
              };
            };
          })
          this.currentPage = jsonResult.data.currentPage;
          this.pageSize = jsonResult.data.pageSize;
          this.total = jsonResult.data.total;
          console.log('用户列表数据：', this.tableData);
          console.log('当前页码：', this.currentPage);
          console.log('每页显示条数：', this.pageSize);
          console.log('总条数：', this.total);
        } else {
          let title = '操作失败';
          this.$alert(jsonResult.message, title, {
            confirmButtonText: '确定',
            callback: action => {
            }
          })
        }
      })
    }
  },
  mounted() {
    let page = this.$route.query.page; // 通过 $route 获取当前页码
    this.loadUserList(page); // 将当前页码传递给 loadUserList 方法
    let url = BaseUrl.ADMIN_CONTENT + '/admin/type/listParentCategory';
    TokenAxios.get(url).then((response) => {
      let jsonResult = response.data;
      if (jsonResult.state == 20000){
        this.parentTableData = jsonResult.data;
      }
    })
  }

}
</script>

<template>
<div>
  <!--面包屑导航区域-->
  <el-breadcrumb separator-class="el-icon-arrow-right" style="margin-bottom: 20px;overflow: hidden">
    <el-breadcrumb-item :to="{ path: '/admin/index' }">首页</el-breadcrumb-item>
    <el-breadcrumb-item>分类管理</el-breadcrumb-item>
  </el-breadcrumb>

  <el-button
      type="primary" style="margin-bottom: 20px" @click="addDialogVisible = true" size="medium">新增标签
  </el-button>
  <el-dialog
      style="text-align: center"
      title="新增标签"
      width="40%"
      :visible.sync="addDialogVisible"
  >
    <el-radio-group v-model="ruleForm.isParent">
      <el-radio  label="1">父类</el-radio>
      <el-radio  label="0">子类</el-radio>
    </el-radio-group>

    <el-form v-if="ruleForm.isParent === '0'">
      <el-form-item label="子类选择框">
        <!-- 在这里添加子类选择框的内容 -->
        <!-- 例如： -->
        <el-select v-model="ruleForm.parentId">
          <!-- 这里放子类的选项 -->
          <el-option v-for="item in parentTableData"
                     :key="item.id"
                     :label="item.name"
                     :value="item.id"/>

          <!-- 更多子类选项 -->
        </el-select>
      </el-form-item>
    </el-form>

    <el-form :model="ruleForm" :rules="rules" ref="ruleForm" >
      <el-form-item label="分类名" prop="name">


    <template>
      <el-input mode="tags" placeholder="请输入分类(限制长度为2-4)"
               size="large" v-model="ruleForm.name"></el-input>
      <br>
    </template>

      </el-form-item>



      <el-radio-group v-model="ruleForm.isDisplay">
        <el-radio  label="0">不显示</el-radio>
        <el-radio  label="1">显示</el-radio>
      </el-radio-group>

    </el-form>
    <el-button @click="addDialogVisible = false">取 消</el-button>
    <el-button
        type="primary" @click="addNewTagsById('ruleForm')" size="small" style="margin-top: 20px"
    >确 定</el-button>
  </el-dialog>

  <el-card>
    <el-table :data="tableData"
              border stripe
              style="margin-bottom: 20px;overflow: hidden">
      <el-table-column type="index" label="#"></el-table-column>
      <el-table-column
          prop="id"
          label="分类id"
     >
      </el-table-column>
      <el-table-column
          prop="name"
          label="类型名称"
          >
      </el-table-column>
      <el-table-column
          prop="isParent"
          label="级别"
      >
        <template slot-scope="scope">
          <el-tag :type="scope.row.isParent.type">{{ scope.row.isParent.text }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column
          prop="isDisplay"
          label="是否显示"
         >
          <template slot-scope="scope">
            <el-tag :type="scope.row.isDisplay.type">{{ scope.row.isDisplay.text }}</el-tag>
          </template>
      </el-table-column>
      <el-table-column
          prop="createTime"
          label="创建时间"
      >
      </el-table-column>
      <el-table-column
          prop="updateTime"
          label="修改时间"
      >
      </el-table-column>
      <el-table-column
          label="操作"
          width="220">
        <template slot-scope="scope">
          <!-- 删除文章按钮 -->
          <el-button
              type="danger"
              icon="el-icon-delete"
              size="mini"
              @click="deleteTagsById(scope.row)"
          ></el-button>
          <el-tooltip
              class="item"
              effect="dark"
              content="修改分类名"
              placement="top"
              enterable
          >
            <el-button
                type="warning"
                icon="el-icon-setting"
                size="mini"
                @click="openUpdateTypeById(scope.row)"
            ></el-button>

          </el-tooltip>
        </template>
      </el-table-column>
    </el-table>
    <!--分页区域-->
    <el-pagination
        @current-change="handleCurrentChange"
        :current-page="currentPage"
        :hide-on-single-page="true"
        :page-size="pageSize"
        layout="total, prev, pager, next,jumper"
        :total="total"
        background
    >
    </el-pagination>

    <el-dialog
        style="text-align: center"
        title="修改分类"
        width="40%"
        :visible.sync="openUpdateTypeByIds"
    >

      <el-radio-group v-model="update.isParent">
        <el-radio  label="1">父类</el-radio>
        <el-radio  label="0">子类</el-radio>
      </el-radio-group>

      <el-form v-if="update.isParent === '0'">
        <el-form-item label="子类选择框">
          <!-- 在这里添加子类选择框的内容 -->
          <!-- 例如： -->
          <el-select v-model="update.parentId">
            <!-- 这里放子类的选项 -->
            <el-option v-for="item in parentTableData"
                       :key="item.id"
                       :label="item.name"
                       :value="item.id"/>

            <!-- 更多子类选项 -->
          </el-select>
        </el-form-item>
      </el-form>
    <el-form :model="update" :rules="types" ref="update" >
      <el-form-item label="分类名" prop="name">
        <template>
          <el-input mode="tags" placeholder="请输入分类(限制长度为2-4)"
                    size="large" v-model="update.name"></el-input>
          <br>
        </template>
      </el-form-item>

      <el-radio-group v-model="update.isDisplay">
        <el-radio  label="0">不显示</el-radio>
        <el-radio  label="1">显示</el-radio>
      </el-radio-group>


    </el-form>
    <el-button @click="openUpdateTypeByIds = false">取 消</el-button>
    <el-button
        type="primary" @click="updateCategoryNameById(update)" size="small" style="margin-top: 20px"
    >确 定</el-button>
    </el-dialog>

  </el-card>

</div>
</template>

<style scoped>

</style>